#include <Arduino.h>
#include <unity.h>
#include "../src/SimpleCDBUS.h"

// Mock serial for testing
class MockSerial : public HardwareSerial {
public:
    MockSerial() : HardwareSerial(0) {}
    void begin(unsigned long baud) override {}
    void end() override {}
    size_t write(uint8_t c) override { return 1; }
    int available() override { return 0; }
    int read() override { return -1; }
    int peek() override { return -1; }
    void flush() override {}
    operator bool() override { return true; }
};

SimpleCDBUS cdbus;
MockSerial mockSerial;

void test_initialization() {
    TEST_ASSERT_FALSE(cdbus.isInitialized());
    cdbus.begin(&mockSerial, 0x01);
    TEST_ASSERT_TRUE(cdbus.isInitialized());
    TEST_ASSERT_EQUAL(0x01, cdbus.getAddress());
    cdbus.end();
    TEST_ASSERT_FALSE(cdbus.isInitialized());
}

void test_address_validation() {
    cdbus.begin(&mockSerial, 0x00);  // Broadcast address
    TEST_ASSERT_TRUE(cdbus.isInitialized());
    cdbus.end();
    
    cdbus.begin(&mockSerial, 0xFF);  // Max address
    TEST_ASSERT_TRUE(cdbus.isInitialized());
    cdbus.end();
}

void test_send_data() {
    cdbus.begin(&mockSerial, 0x01);
    uint8_t data[] = {0x01, 0x02, 0x03};
    
    // Test basic send
    cdbus.send(0x02, data, 3);
    
    // Test empty data
    cdbus.send(0x02, nullptr, 0);
    
    // Test max length
    uint8_t longData[253];
    cdbus.send(0x02, longData, 253);
    
    cdbus.end();
}

void test_set_baud_rate() {
    cdbus.begin(&mockSerial, 0x01);
    
    cdbus.setBaudRate(9600);
    cdbus.setBaudRate(115200);
    cdbus.setBaudRate(1000000);
    
    cdbus.end();
}

void test_filter_settings() {
    cdbus.begin(&mockSerial, 0x01);
    
    cdbus.setFilter(0);  // Accept all
    cdbus.setFilter(1);  // Filter enabled
    
    cdbus.end();
}

void setup() {
    UNITY_BEGIN();
    RUN_TEST(test_initialization);
    RUN_TEST(test_address_validation);
    RUN_TEST(test_send_data);
    RUN_TEST(test_set_baud_rate);
    RUN_TEST(test_filter_settings);
    UNITY_END();
}

void loop() {
    // Empty - tests run in setup
}